<!-- 创建时间: 2020年12月23日 Wednesday 09:32 -->
<template>
    <div class="login_container">
        <img src="images/login_background.jpg"
             id="login_background" />
        <div class="whiteBox">
            <center>
                <h3>欢迎登录小花考试系统</h3>
            </center>
            <el-input placeholder="请输入账号"
                      v-model="form.userNumebr"
                      clearable>
            </el-input>
            <p></p>
            <el-input placeholder="请输入密码"
                      v-model="form.userPass"
                      show-password></el-input>
            <br />
            <span v-show="pagePromptInformation.showUserInfoError"
                  class="userInfoError">{{ pagePromptInformation.message }}</span>
            <p></p>
            <el-radio-group v-model="form.userType">
                <el-radio label="学生"></el-radio>
                <el-radio label="教师"></el-radio>
            </el-radio-group>
            <p></p>
            <el-row>
                <el-col :span="12">
                    <el-input v-model="form.verCode"
                              placeholder="请输入验证码"
                              clearable
                              @keyup.enter.native="verCodeKeyDown()"
                              ref="verCode"></el-input>
                </el-col>
                <el-col :span="12">
                    <canvas id="canvas"
                            width="100px"
                            height="30px"
                            @click="getVerCode()"></canvas>
                </el-col>
            </el-row>
            <span class="codeError"
                  v-show="pagePromptInformation.showCodeError">{{ pagePromptInformation.message }}</span>
            <p></p>
            <center>
                <el-button style="width: 50%"
                           type="primary"
                           plain
                           @click="login()">登录</el-button>
            </center>
        </div>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import Vue from "vue";
import md5 from "../../js/md5";
import $ from "jquery";
import JSEncrypt from "jsencrypt";
import localforage from "localforage";

export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data () {
        //这里存放数据
        return {
            form: {
                userNumebr: "2006831517",
                userPass: "123456",
                verCode: "",
                userType: "教师",
            },
            pubKey: "", // 公钥

            pagePromptInformation: {
                showUserInfoError: false, // 显示隐藏用户信息错误
                showCodeError: false,
                message: "",
            },
        };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        login () {
            if (this.form.userNumebr.length != 10) {
                alert("非法账号!");
                return;
            }
            let userClass = this.form.userNumebr.substring(0, 7);
            this.$http.get("getPubKey").then((res) => {
                this.pubKey = res.bodyText;
                let encrypt = new JSEncrypt();
                encrypt.setPublicKey(this.pubKey);
                let rsaPass = encrypt.encrypt(md5(this.form.userPass));
                let type = this.form.userType == "学生" ? 0 : 1;
                localforage.getItem("_c").then((val) => {
                    this.$http
                        .post("login", {
                            userid: this.form.userNumebr,
                            userclass: userClass,
                            userpass: rsaPass,
                            type: type,
                            code: JSON.stringify({
                                code: this.form.verCode,
                                _c: val == null ? "" : val,
                            }),
                        })
                        .then((res) => {
                            switch (res.body[0]) {
                                case "-1": // 验证码过期
                                    this.pagePromptInformation.showCodeError = true;
                                    this.pagePromptInformation.showUserInfoError = false;
                                    this.pagePromptInformation.message =
                                        "验证码过期";
                                    this.getVerCode();
                                    break;
                                case "0": // 验证码错误
                                    this.pagePromptInformation.showCodeError = true;
                                    this.pagePromptInformation.showUserInfoError = false;
                                    this.pagePromptInformation.message =
                                        "验证码错误";
                                    this.getVerCode();
                                    break;
                                case "1": // 用户信息错误
                                    this.pagePromptInformation.showUserInfoError = true;
                                    this.pagePromptInformation.showCodeError = false;
                                    this.pagePromptInformation.message =
                                        "*用户名或密码错误";
                                    if (res.body[1] != undefined) {
                                        let obj = {
                                            LOGIN_STATUS_LOCK_TOTAL: res.body[1],
                                            LOGIN_STATUS_LOCK_COUNT: res.body[2],
                                        };
                                        if (
                                            obj.LOGIN_STATUS_LOCK_TOTAL -
                                            obj.LOGIN_STATUS_LOCK_COUNT !=
                                            0
                                        )
                                            alert(
                                                "密码错误，您还有" +
                                                (obj.LOGIN_STATUS_LOCK_TOTAL -
                                                    obj.LOGIN_STATUS_LOCK_COUNT) +
                                                "次尝试机会！如忘记密码，请与学院教学秘书或辅导员联系初始化账户密码！"
                                            );
                                        else
                                            this.$message({
                                                message: "您的账户已被锁定，请24小时后再试！",
                                                type: "warning",
                                            });
                                    }
                                    this.getVerCode();
                                    break;
                                case "2": // 登录成功
                                    if (
                                        JSON.parse(
                                            JSON.parse(res.body[2]).token ==
                                            "true"
                                        )
                                    ) {
                                        sessionStorage.setItem("flag", false);
                                    } else {
                                        sessionStorage.setItem("flag", true);
                                    }
                                    if (type) {
                                        sessionStorage.setItem(
                                            this.form.userNumebr,
                                            res.body[2]
                                        );
                                        this.$store.commit(
                                            "setUserName",
                                            res.body[1]
                                        );
                                        this.$store.commit(
                                            "setUserNumber",
                                            this.form.userNumebr
                                        );
                                        this.$store.commit(
                                            "setUserType",
                                            "teacher"
                                        );
                                        this.$router.push({
                                            path: "/teacher",
                                        });
                                    } else {
                                        sessionStorage.setItem(
                                            this.form.userNumebr,
                                            res.body[2]
                                        );
                                        this.$store.commit(
                                            "setUserName",
                                            res.body[1]
                                        );
                                        this.$store.commit(
                                            "setUserNumber",
                                            this.form.userNumebr
                                        );
                                        this.$store.commit(
                                            "setUserType",
                                            "student"
                                        );
                                        this.$router.push("/student");
                                    }
                                    break;
                                case "3":
                                    sessionStorage.removeItem("flag");
                                    sessionStorage.removeItem("token");
                                    this.$message({
                                        message: "您的账户已被锁定，请24小时后再试！",
                                        type: "warning",
                                    });
                                    break;
                                default:
                                    break;
                            }
                            setTimeout(() => {
                                this.showCodeError = false;
                                this.showUserInfoError = false;
                            }, 4000);
                        });
                });
            });
        },

        // 获取验证码
        getVerCode () {
            let canvas = document.getElementById("canvas");
            let context = canvas.getContext("2d");
            /**清除画布 */
            context.clearRect(0, 0, canvas.width, canvas.height);
            let img = new Image();

            localforage.getItem("_c").then((val) => {
                this.$http.post("getCode", {
                    val: val
                }).then((res) => {
                    img.src = res.body.code;
                    localforage.setItem("_c", res.body._c);
                    let dt = setTimeout(() => {
                        localforage.removeItem("_c");
                        clearTimeout(dt);
                    }, 1000 * 60 * 3);
                });
            });

            // img.src = this.$ROOT + "/getCode?uptime=" + new Date().getTime();
            /**填充文本 */
            context.font = "20px sans-serif";
            context.fillStyle = "black";
            // 参数：文本内容，开始绘制x,y,最大宽度
            context.fillText("Loading...", 0, 20);
            img.onload = function () {
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.drawImage(img, 0, 0);
            };
        },
        verCodeKeyDown () {
            this.login();
        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created () { },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted () {
        this.getVerCode();
        if (this.$route.params.status != undefined) {
            this.$message({
                message: this.$route.params.status,
                type: this.$route.params.type,
            });
        }
    },
    //当data中定义的数据有变化时就会加载updated方法
    updated () { },
};
</script>

<style lang="scss" scoped>
//@import url(); 引入公共css类
.login_container {
    img {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-size: 100%;
        object-fit: cover;
        z-index: -1;
        user-select: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
    }

    .whiteBox {
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        margin: auto;
        width: 350px;
        height: 335px;
        background: rgba(255, 255, 255, 0.6);
        backdrop-filter: blur(8px);
        border-radius: 7px;
        box-shadow: 0px 0px 2px #fff;
        padding: 20px;

        h3 {
            color: cornflowerblue;
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
        }

        #canvas {
            border: 0px salmon solid;
            margin-left: 10px;
            cursor: pointer;
        }
    }
}
</style>
